# -*- coding: utf-8 -*-
"""
Created on Sat May 26 15:36:12 2018

@author: wg
"""
import sys,os,dlib,glob,numpy
from skimage import io
def predict():
    
    
    # 1.人脸关键点检测器
    predictor_path = "shape_predictor_68_face_landmarks.dat"
    # 2.人脸识别模型
    face_rec_model_path = "dlib_face_recognition_resnet_model_v1.dat"
    # 3.候选人脸文件夹
    faces_folder_path = "database"
    
    img_path = "t1.jpg"
    facerec = dlib.face_recognition_model_v1(face_rec_model_path)
    
    detector = dlib.get_frontal_face_detector()
    
    sp = dlib.shape_predictor(predictor_path)
    
    
    
    descriptors = []
    
    
    for f in glob.glob(os.path.join(faces_folder_path, "*.jpg")):
        print("正在处理： {}".format(f))
        img = io.imread(f)
        dets = detector(img, 1)
        print("人脸数量： {}".format(len(dets)))
        for k, d in enumerate(dets): 
    
              shape = sp(img, d)
    
              face_descriptor = facerec.compute_face_descriptor(img, shape)
    
              v = numpy.array(face_descriptor) 
              descriptors.append(v)
    
    img = io.imread(img_path)
    dets = detector(img, 1)
    dist = []
    for k, d in enumerate(dets):
        shape = sp(img, d)
        face_descriptor = facerec.compute_face_descriptor(img, shape)
        d_test = numpy.array(face_descriptor) 
    
        for i in descriptors:
            dist_ = numpy.linalg.norm(i-d_test)
            dist.append(dist_)
    
    print(dist)
    predict = []
    for i in range(len(dist)):
        if dist[i]<0.3:
            predict.append(1)
            
            
        
        else:
            predict.append(0)
    person = os.listdir("database")
    print(person)
    print(predict)
    zhong = ""
    for i in range(len(predict)):
        if predict[i] == 1:
            zhong = person[i][len(zhong):len(zhong)-4]
            break
            
    return zhong